package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.controller.param.CreatePrizeParam;
import com.example.lotterysystem.controller.param.PageParam;
import com.example.lotterysystem.dao.dataobject.PrizeDO;
import com.example.lotterysystem.dao.mapper.PrizeMapper;
import com.example.lotterysystem.service.IPictureService;
import com.example.lotterysystem.service.IPrizeService;
import com.example.lotterysystem.service.dto.PageListDTO;
import com.example.lotterysystem.service.dto.PrizeDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/30
 */
@Slf4j
@Service
public class PrizeServiceImpl implements IPrizeService {
    @Autowired
    private PrizeMapper prizeMapper;

    @Autowired
    private IPictureService pictureService;

    @Override
    public Long createPrize(Integer createId,CreatePrizeParam param, MultipartFile picFile) {
        if (param == null) {
            throw new ServiceException(ServiceErrorCodeConstants.PARAM_ERROR);
        }
        //上传图片
        String filename = pictureService.savePicture(picFile);
        //构造对象
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setPrice(param.getPrice());
        prizeDO.setImageUrl(filename);
        //存储数据库
        prizeMapper.createPrize(createId,prizeDO);
        return prizeDO.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> selectPrizeByPage(Integer userId, PageParam param) {
        //总数
        int total = prizeMapper.count(userId);
        //当前页列表
        List<PrizeDTO> prizeDTOList = new ArrayList<>();
        List<PrizeDO> prizeDOList = prizeMapper.
                selectPrizeListByPage(userId, param.offset(), param.getPageSize());
        for (PrizeDO prizeDO : prizeDOList) {
            PrizeDTO prizeDTO = new PrizeDTO();
            prizeDTO.setPriceId(prizeDO.getId());
            prizeDTO.setName(prizeDO.getName());
            prizeDTO.setDescription(prizeDO.getDescription());
            prizeDTO.setImageUrl(prizeDO.getImageUrl());
            prizeDTO.setPrice(prizeDO.getPrice());
            prizeDTOList.add(prizeDTO);
        }
        return new PageListDTO<>(total, prizeDTOList);
    }


}
